package io.renren.modules.api.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import io.renren.modules.api.dao.DriverTokenDao;
import io.renren.modules.api.entity.DriverTokenEntity;
import io.renren.modules.api.service.DriverTokenService;



@Service("driverTokenService")
public class DriverTokenServiceImpl implements DriverTokenService {
	@Autowired
	private DriverTokenDao driverTokenDao;

	//12小时后过期
	private final static int EXPIRE = 3600 * 12;
	
	@Override
	public DriverTokenEntity queryObject(Long driverId){
		return driverTokenDao.queryObject(driverId);
	}

	@Override
	public DriverTokenEntity queryByToken(String token) {
		return driverTokenDao.queryByToken(token);
	}

	@Override
	public List<DriverTokenEntity> queryList(Map<String, Object> map){
		return driverTokenDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return driverTokenDao.queryTotal(map);
	}
	
	@Override
	public void save(DriverTokenEntity driverToken){
		driverTokenDao.save(driverToken);
	}
	
	@Override
	public void update(DriverTokenEntity driverToken){
		driverTokenDao.update(driverToken);
	}
	
	@Override
	public void delete(Long driverId){
		driverTokenDao.delete(driverId);
	}
	
	@Override
	public void deleteBatch(Long[] driverIds){
		driverTokenDao.deleteBatch(driverIds);
	}

	@Override
	public Map<String, Object> createToken(long driverId, String type) {
		//生成一个token
		String token = type.concat(UUID.randomUUID().toString());
		//当前时间
		Date now = new Date();

		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		DriverTokenEntity driverTokenEntity = queryObject(driverId);
		if(driverTokenEntity == null){
			driverTokenEntity = new DriverTokenEntity();
			driverTokenEntity.setDriverId(driverId);
			driverTokenEntity.setToken(token);
			driverTokenEntity.setUpdateTime(now);
			driverTokenEntity.setExpireTime(expireTime);

			//保存token
			save(driverTokenEntity);
		}else{
			driverTokenEntity.setToken(token);
			driverTokenEntity.setUpdateTime(now);
			driverTokenEntity.setExpireTime(expireTime);

			//更新token
			update(driverTokenEntity);
		}

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("expire", EXPIRE);

		return map;
	}



}
